package com.zwb.boot.common.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author 头发又黑又长
 * @Date 2022/7/27 19:01
 * @email zwb15083976291@163.com
 */
@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 获取 字符串类型数据
     *
     * @param key
     * @return
     */
    public String getStr(String key) {
        Object o = redisTemplate.opsForValue().get(key);
        if (ObjectUtils.isEmpty(o)) {
            return null;
        }
        return (String) o;
    }

    /**
     * 获取 数据
     *
     * @param key
     * @return
     */
    public Object get(Object key) {
        return redisTemplate.opsForValue().get(key);
    }


    /**
     * 设置值
     *
     * @param key
     * @param val
     * @return
     */
    public void set(Object key, Object val) {
        redisTemplate.opsForValue().set(key, val);
    }

    /**
     * 设置过期时间，单位秒
     *
     * @param key
     * @param val
     * @param timeOutSecond
     */
    public void setWithExpir(Object key, Object val, Long timeOutSecond) {
        this.redisTemplate.opsForValue().set(key, val, timeOutSecond, TimeUnit.SECONDS);
    }


    /**
     * 获取剩余时间
     *
     * @param key
     * @return
     */
    public Long getExpir(Object key) {

        return this.redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }


    /**
     * 删除指定的key
     *
     * @param key
     * @return
     */
    public boolean del(Object key) {
        return this.redisTemplate.delete(key);
    }


    /**
     * 删除并返回
     *
     * @param key
     * @return
     */
    public Object getAndDelete(Object key) {
        Object o = this.redisTemplate.opsForValue().get(key);
        this.redisTemplate.delete(key);
        return o;
    }

}
